package binarytree;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

/**
 * @Author: 海琳琦
 * @Date: 2022/2/19 15:06
 * https://leetcode-cn.com/problems/invert-binary-tree/
 * 给你一棵二叉树的根节点 root ，翻转这棵二叉树，并返回其根节点。
 */
public class InvertTree {

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    /**
     * 层次遍历
     * @param root
     * @return
     */
    public TreeNode invertTree(TreeNode root) {
        Queue<TreeNode> levelNode = new LinkedList<>();
        if (root != null) {
            levelNode.offer(root);
        }
        while (!levelNode.isEmpty()) {
            int size = levelNode.size();
            for (int i = 0; i < size; i++) {
                TreeNode poll = levelNode.poll();
                TreeNode temp = poll.right;
                poll.left = poll.right;
                poll.right = temp;
                if (poll.left != null) {
                    levelNode.offer(poll.left);
                }
                if (poll.right != null) {
                    levelNode.offer(poll.right);
                }
            }
        }
        return root;
    }

    /**
     * 递归遍历           前序或者后序遍历都可以，中序不行（重点：交换每个节点的左右孩子）
     * @param root
     * @return
     */
    public TreeNode invertTree1(TreeNode root) {
        if (root == null) {
            return root;
        }
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }


    /**
     * 前序遍历
     * @param root
     * @return
     */
    public TreeNode invertTree2(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        if (root != null) {
            stack.push(root);
        }
        while (!stack.isEmpty()) {
            TreeNode pop = stack.pop();
            TreeNode temp = pop.left;
            pop.left = pop.right;
            pop.right = temp;
            if (pop.right != null) {
                stack.push(pop.right);
            }
            if (pop.left != null) {
                stack.push(pop.left);
            }
        }
        return root;
    }

    public void reverseTree(TreeNode root) {

    }

    public static void main(String[] args) {

    }
}
